package com.zys.http.processor.jaxrs;

import cn.hutool.core.text.CharSequenceUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.zys.http.constant.HttpEnum;
import com.zys.http.entity.param.ParamProperty;
import com.zys.http.entity.tree.MethodNodeData;
import com.zys.http.entity.velocity.MethodItem;
import com.zys.http.processor.AbstractJavaApiProcessor;
import com.zys.http.tool.UrlTool;
import com.zys.http.tool.VelocityTool;
import com.zys.http.ui.tree.node.MethodNode;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * @author zhou ys
 * @since 2024-05-21
 */
public class JaxRsJavaApiProcessor extends AbstractJavaApiProcessor {
    private static final String CONSUMES_1 = "javax.ws.rs.Consumes";
    private static final String CONSUMES_2 = "jakarta.ws.rs.Consumes";
    public static final JaxRsJavaApiProcessor INSTANCE = new JaxRsJavaApiProcessor();

    @Override
    public List<? extends PsiElement> controllers(Project project, Module module) {
        Optional<GlobalSearchScope> scopeOp = Optional.of(module).map(Module::getModuleScope);
        Collection<PsiAnnotation> annotations = ApplicationManager.getApplication().runReadAction((Computable<Collection<PsiAnnotation>>) () -> {
            Collection<PsiAnnotation> all = new ArrayList<>();
            for (JaxRsEnums.Controller controller : JaxRsEnums.Controller.values()) {
                String shortClassName = controller.getShortClassName();
                all.addAll(scopeOp.map(ms -> JavaAnnotationIndex.getInstance().get(shortClassName, project, ms)).orElse(new ArrayList<>()));
            }
            return all;
        });

        return annotations.stream()
                .map(PsiElement::getParent)
                .map(PsiModifierList.class::cast)
                .map(PsiModifierList::getParent)
                .filter(PsiClass.class::isInstance)
                .map(PsiClass.class::cast)
                .toList();
    }

    @Override
    public String controllerPath(PsiElement psiElement) {
        if (!(psiElement instanceof PsiClass psiClass)) {
            return "";
        }
        PsiModifierList modifierList = psiClass.getModifierList();
        if (Objects.isNull(modifierList)) {
            return "";
        }

        PsiAnnotation[] annotations = modifierList.getAnnotations();

        for (PsiAnnotation annotation : annotations) {
            if (JaxRsEnums.Controller.PATH_1.getClazz().equals(annotation.getQualifiedName())) {
                return annotationValue(annotation, new String[]{VALUE_KEY});
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().equals(annotation.getQualifiedName())) {
                return annotationValue(annotation, new String[]{VALUE_KEY});
            }
        }
        return "";
    }

    @Override
    public String methodPath(PsiElement element) {
        if (!(element instanceof PsiMethod method)) {
            return null;
        }
        PsiAnnotation[] annotations = method.getAnnotations();

        for (PsiAnnotation annotation : annotations) {
            if (JaxRsEnums.Controller.PATH_1.getClazz().equals(annotation.getQualifiedName())) {
                return annotationValue(annotation, new String[]{VALUE_KEY});
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().equals(annotation.getQualifiedName())) {
                return annotationValue(annotation, new String[]{VALUE_KEY});
            }
        }
        return null;
    }

    @Override
    protected MethodNode createMethodNode(PsiMethod method, String controllerPath, String contextPath) {
        PsiAnnotation[] annotations = method.getAnnotations();

        PsiAnnotation pathAnno = null;
        PsiAnnotation methodAnno = null;

        for (PsiAnnotation annotation : annotations) {
            if (JaxRsEnums.Controller.PATH_1.getClazz().equals(annotation.getQualifiedName())) {
                pathAnno = annotation;
            }

            if (JaxRsEnums.Controller.PATH_2.getClazz().equals(annotation.getQualifiedName())) {
                pathAnno = annotation;
            }

            if (JaxRsEnums.Method.contains(annotation)) {
                methodAnno = annotation;
            }
            if (Objects.nonNull(pathAnno) && Objects.nonNull(methodAnno)) {
                break;
            }
        }
        if (Objects.isNull(pathAnno) || Objects.isNull(methodAnno)) {
            return null;
        }
        String name = annotationValue(pathAnno, new String[]{VALUE_KEY});
        HttpEnum.HttpMethod httpMethod = JaxRsEnums.Method.get(methodAnno);
        MethodNodeData data = new MethodNodeData(httpMethod, name, controllerPath, contextPath);
        data.setDescription(methodSwagger(method));
        data.setPsiElement(method);
        return new MethodNode(data);
    }

    @Override
    protected void parameterParse(@NotNull PsiParameter parameter, @NotNull Map<String, ParamProperty> map, boolean isJsonPretty) {
        String parameterName = parameter.getName();
        PsiType parameterType = parameter.getType();

        // 1 如果有 @HeaderParam 注解
        headerParamValue(parameter, map);

        // 2 如果有 @QueryParam 注解
        HttpEnum.ParamUsage paramUsage = HttpEnum.ParamUsage.URL;
        PsiAnnotation anno = parameter.getAnnotation(JaxRsEnums.Param.QUERY_PARAM_1.getClazz());
        if (anno != null) {
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
        }
        anno = parameter.getAnnotation(JaxRsEnums.Param.QUERY_PARAM_2.getClazz());
        if (anno != null) {
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
        }

        // 3 如果有 @PathParam 注解
        anno = parameter.getAnnotation(JaxRsEnums.Param.PATH_PARAM_1.getClazz());
        if (anno != null) {
            paramUsage = HttpEnum.ParamUsage.PATH;
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
        }
        anno = parameter.getAnnotation(JaxRsEnums.Param.PATH_PARAM_2.getClazz());
        if (anno != null) {
            paramUsage = HttpEnum.ParamUsage.PATH;
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
        }

        Object paramDefaultTypeValue = typeDefaultValue(parameter.getProject(), parameterType);
        if (Objects.isNull(paramDefaultTypeValue)) {
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            return;
        }
        PsiMethod method = (PsiMethod) parameter.getParent().getParent();
        PsiAnnotation annotation = method.getAnnotation(CONSUMES_1);
        annotation = Objects.isNull(annotation) ? method.getAnnotation(CONSUMES_2) : annotation;
        boolean isJson = false;
        if (Objects.nonNull(annotation)) {
            String s = annotationValue(annotation, new String[]{VALUE_KEY});
            isJson = s.contains(HttpEnum.ContentType.APPLICATION_JSON.getValue()) || "MediaType.APPLICATION_JSON".equals(s);
        }

        parameterParseResult(parameterName, paramDefaultTypeValue, isJson, isJsonPretty, map, paramUsage);
    }

    private void headerParamValue(@NotNull PsiParameter parameter, @NotNull Map<String, ParamProperty> map) {
        String parameterName;
        PsiAnnotation anno = parameter.getAnnotation(JaxRsEnums.Param.HEADER_PARAM_1.getClazz());
        ParamProperty property = map.getOrDefault(REQUEST_TYPE_KEY, null);
        if (property == null) {
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
        }
        if (anno != null) {
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.HEADER));
            return;
        }
        anno = parameter.getAnnotation(JaxRsEnums.Param.HEADER_PARAM_2.getClazz());
        if (anno != null) {
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.HEADER));
        }
    }

    @Override
    protected MethodItem postmanMethodItem(PsiMethod method, String contextPath, String controllerPath) {
        PsiAnnotation[] annotations = method.getAnnotations();
        MethodItem item = new MethodItem();
        // 方法名
        String methodSwagger = methodSwagger(method);
        methodSwagger = CharSequenceUtil.isEmpty(methodSwagger) ? method.getName() : methodSwagger;
        item.setName(methodSwagger);

        // 请求方式、请求uri、请求头类型
        HttpEnum.HttpMethod httpMethod = HttpEnum.HttpMethod.GET;
        String path = "";
        for (PsiAnnotation annotation : annotations) {
            HttpEnum.HttpMethod tmp = JaxRsEnums.Method.get(annotation);
            httpMethod = Objects.isNull(tmp) ? httpMethod : tmp;
            if (JaxRsEnums.Controller.PATH_1.getClazz().equals(annotation.getQualifiedName())) {
                path = annotationValue(annotation, new String[]{VALUE_KEY});
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().equals(annotation.getQualifiedName())) {
                path = annotationValue(annotation, new String[]{VALUE_KEY});
            }
        }

        item.setMethod(httpMethod.name());
        item.setUri(UrlTool.buildMethodUri(contextPath, controllerPath, path));
        // 请求参数类型
        VelocityTool.buildParamProperty(method, item);
        return item;
    }

}
